package com.two.screen.water.balance.ui.activity.presentation

import android.annotation.SuppressLint
import android.app.Presentation
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.Editable
import android.view.Display
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import cn.jzvd.JZDataSource
import cn.jzvd.Jzvd
import cn.jzvd.JzvdStd
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.two.screen.water.balance.R
import com.two.screen.water.balance.adapter.BottomBannerAdapter
import com.two.screen.water.balance.bean.MyTextWatcher
import com.two.screen.water.balance.bean.ResponsePay
import com.two.screen.water.balance.bean.ViceBean
import com.two.screen.water.balance.bean.database.OrderProductDB
import com.two.screen.water.balance.bean.database.ServerOrderResult
import com.two.screen.water.balance.image.ImageManger
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.widget.DividerItemDecoration
import com.two.screen.water.balance.widget.MyJZVideoPlayer
import com.two.screen.water.balance.widget.mybanner.banner.MyBanner
import com.two.screen.water.balance.widget.mybanner.banner.transformer.ZoomOutPageTransformer
import com.xl.ratingbar.MyRatingBar
import com.youth.banner.Banner
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import me.grantland.widget.AutofitTextView
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.util.concurrent.TimeUnit

class ViceScreenDisplay(var mContext: Context, display: Display?) : Presentation(mContext, display) {

    lateinit var mHadChooseAdapter: HadChooseAdapter
    private var mBottomBannerAdapter: BottomBannerAdapter? = null

    private var mNoAwaitRootLayout: View? = null
    private var mAwaitRootLayout: View? = null

    /*待机*/
    private var mAwaitLogoIv: ImageView? = null
    private var mAwaitContactNameAtv: AutofitTextView? = null
    private var mAwaitStallNameAtv: AutofitTextView? = null
    private var mAwaitMyRB: MyRatingBar? = null
    private var mAwaitOnlineQrIv: ImageView? = null
    private var mAwaitOnlineTipsTv: TextView? = null
    private var mAwaitLeftBottomTipsAtv: AutofitTextView? = null
    private var mAwaitAboutMeQrIv: ImageView? = null
    private var mBanner: Banner? = null
    private var mEmptyFoodLayout: View? = null
    private var mJzVideo: MyJZVideoPlayer? = null

    /*非待机*/
    private var mLogoIv: ImageView? = null
    private var mContactNameAtv: AutofitTextView? = null
    private var mStallNameAtv: AutofitTextView? = null
    private var mMyRB: MyRatingBar? = null
    private var mWetchAliPayLayout: View? = null
    private var mWetchPayBgIv: ImageView? = null
    private var mWetchPayIv: ImageView? = null
    private var mAliPayBgIv: ImageView? = null
    private var mAliPayIv: ImageView? = null
    private var mJuHeStaticPayLayout: View? = null
    private var mJuHeStaticPayBgIv: ImageView? = null
    private var mJuHeStaticPayIv: ImageView? = null
    private var mJuHeDynamicPayLayout: View? = null
    private var mJuHeDynamicPayIv: ImageView? = null
    private var mJuHeDynamicPayTv: AutofitTextView? = null
    private var mVipPayLayout: View? = null
    private var mVipPayBgIv: ImageView? = null
    private var mJuHeDynamicPayBgIv: ImageView? = null
    private var mVipPayTv: AutofitTextView? = null
    private var mVipPayIv: ImageView? = null
    private var mBottomTipsTv: TextView? = null
    private var mChooseFoodAtv: AutofitTextView? = null
    private var mRightWeightTv: AutofitTextView? = null
    private var mRightUnitPriceTv: AutofitTextView? = null
    private var mSubTotalTv: AutofitTextView? = null
    private var mHadChooseRecyclerView: RecyclerView? = null
    private var mTotalPriceTv: TextView? = null
    private var mRightBottomBanner: Banner? = null
    private var mIntegralAndTraceIv: ImageView? = null
    private var mIntegralAndTraceTv: TextView? = null
    private var mRightBottomTipsBanner: MyBanner<OrderProductDB, BottomBannerAdapter>? = null

    /*当前多时间了，准备进入待机*/
    private var mCurLeftTime = 0L;
    private var mDisposable: Disposable? = null;

    /*logo Bitmap*/
    var mAppLogoBitmap: Bitmap? = null

    /*视频、图片播放*/
    private var mMediaDisposable: Disposable? = null
    private var mMediaCount = 1 //当前计数器
    private var mCurPlayType = PLAY_TYPE_EMPTY //当前播放类型->

    companion object {
        val PLAY_TYPE_EMPTY = 0
        val PLAY_TYPE_VIDEO = 1
        val PLAY_TYPE_BANNER = 2
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.presentation_vice_screen)
        /*这里svg转成null*/
        mAppLogoBitmap = ImageManger.getBitmap(mContext, R.drawable.app_logo)
        initView()
        initData()
        initListener()
    }

    private fun initView() {
        mNoAwaitRootLayout = findViewById(R.id.mNoAwaitRootLayout)
        mAwaitRootLayout = findViewById(R.id.mAwaitRootLayout)
        mAwaitStallNameAtv = findViewById(R.id.mAwaitStallNameAtv)
        mAwaitMyRB = findViewById(R.id.mAwaitMyRB)
        mAwaitOnlineQrIv = findViewById(R.id.mAwaitOnlineQrIv)
        mAwaitOnlineTipsTv = findViewById(R.id.mAwaitOnlineTipsTv)
        mAwaitLogoIv = findViewById(R.id.mAwaitLogoIv)
        mAwaitContactNameAtv = findViewById(R.id.mAwaitContactNameAtv)
        mAwaitLeftBottomTipsAtv = findViewById(R.id.mAwaitLeftBottomTipsAtv)
        mAwaitAboutMeQrIv = findViewById(R.id.mAwaitAboutMeQrIv)
        mBanner = findViewById(R.id.mBanner)
        mEmptyFoodLayout = findViewById(R.id.mEmptyFoodLayout)
        mJzVideo = findViewById(R.id.mJzVideo)

        mContactNameAtv = findViewById(R.id.mContactNameAtv)
        mLogoIv = findViewById(R.id.mLogoIv)
        mStallNameAtv = findViewById(R.id.mStallNameAtv)
        mMyRB = findViewById(R.id.mMyRB)
        mWetchAliPayLayout = findViewById(R.id.mWetchAliPayLayout)
        mWetchPayBgIv = findViewById(R.id.mWetchPayBgIv)
        mWetchPayIv = findViewById(R.id.mWetchPayIv)
        mAliPayBgIv = findViewById(R.id.mAliPayBgIv)
        mAliPayIv = findViewById(R.id.mAliPayIv)
        mJuHeStaticPayLayout = findViewById(R.id.mJuHeStaticPayLayout)
        mJuHeStaticPayBgIv = findViewById(R.id.mJuHeStaticPayBgIv)
        mJuHeStaticPayIv = findViewById(R.id.mJuHeStaticPayIv)
        mJuHeDynamicPayLayout = findViewById(R.id.mJuHeDynamicPayLayout)
        mJuHeDynamicPayBgIv = findViewById(R.id.mJuHeDynamicPayBgIv)
        mJuHeDynamicPayIv = findViewById(R.id.mJuHeDynamicPayIv)
        mJuHeDynamicPayTv = findViewById(R.id.mJuHeDynamicPayTv)
        mVipPayLayout = findViewById(R.id.mVipPayLayout)
        mVipPayBgIv = findViewById(R.id.mVipPayBgIv)
        mVipPayTv = findViewById(R.id.mVipPayTv)
        mVipPayIv = findViewById(R.id.mVipPayIv)
        mBottomTipsTv = findViewById(R.id.mBottomTipsTv)
        mChooseFoodAtv = findViewById(R.id.mChooseFoodAtv)
        mRightWeightTv = findViewById(R.id.mRightWeightTv)
        mRightUnitPriceTv = findViewById(R.id.mRightUnitPriceTv)
        mSubTotalTv = findViewById(R.id.mSubTotalTv)
        mHadChooseRecyclerView = findViewById(R.id.mHadChooseRecyclerView)
        mTotalPriceTv = findViewById(R.id.mTotalPriceTv)
        mRightBottomBanner = findViewById(R.id.mRightBottomBanner)
        mIntegralAndTraceIv = findViewById(R.id.mIntegralAndTraceIv)
        mIntegralAndTraceTv = findViewById(R.id.mIntegralAndTraceTv)
        mRightBottomTipsBanner = findViewById(R.id.mRightBottomTipsBanner)
    }

    private fun initData() {
        if (DataApi.mIsShowViceBanner) {
            initNoAwait()
            initAwait()
            updateAllData()
        } else {
            initNoAwait()
            updateAllData()
        }
    }

    /*初始化非待机*/
    private fun initNoAwait() {
        initOrderRcy()
        initTv()
        initRightBottomBanner()
    }

    /*初始化待机*/
    private fun initAwait() {
        /*初始化 待机的banner*/
        mBanner
            ?.setBannerStyle(BannerConfig.NOT_INDICATOR)
            ?.setDelayTime(DataApi.mPerBannerImgStayTimeArray[DataApi.mPerBannerImgStayTimeIndex].toInt() * 1000)
            ?.setBannerAnimation(CommUtils.getBannerAnimation(DataApi.mViceAwaitBannerAnimationType))
            ?.setImageLoader(object : ImageLoader() {
                override fun displayImage(context: Context?, path: Any?, imageView: ImageView) {
                    imageView.post { ImageManger.setCenterCropImg(mContext, path as String, imageView, 300) }
                }
            })
    }

    /*这里刷新数据*/
    private fun updateAllData(isUpdateVideo: Boolean = true) {
        //下面是测试数据
        showStaticPayIv()
        CommUtils.println("List:=>mViceAwaitBannerListData:", CommUtils.gson.toJson(DataApi.mViceAwaitBannerListData))

        initAwaitQrIv()
        initShopInfo()
        CommUtils.println("List:=>mViceWeightBottomTipsListData:", CommUtils.gson.toJson(DataApi.mViceWeightBottomTipsListData))
        initBottomBanner(DataApi.mViceWeightBottomTipsListData)
        //下面是测试数据
        CommUtils.println("List:=>mViceWeightBannerListData:", CommUtils.gson.toJson(DataApi.mViceWeightBannerListData))
        mRightBottomBanner?.setImages(DataApi.mViceWeightBannerListData)
            ?.setBannerAnimation(CommUtils.getBannerAnimation(DataApi.mViceWeightBannerAnimationType))
            ?.setDelayTime(DataApi.mPerBannerImgStayTimeArray[DataApi.mPerBannerImgStayTimeIndex].toInt() * 1000)
            ?.start()
        setBannerData()
        if (DataApi.mIsShowViceBanner && isUpdateVideo) {
            //视频
            try {
                Jzvd.releaseAllVideos()
            } catch (e: Exception) {

            }
            if (DataApi.mVideoBean != null) setVideoData()
            mCurPlayType = PLAY_TYPE_BANNER
            //pollingMediaRequest()
        }
    }

    @SuppressLint("CheckResult")
    private fun pollingLeftTime2Await() {
        mDisposable?.dispose()
        Observable.create(ObservableOnSubscribe<String> { e ->
            try {
                /* 重量大于0不进入待机 */
                if (mRightWeightTv?.text?.toString()?.toDouble() ?: 0.0 > 0.0) {
                    mCurLeftTime = 0
                }
                mCurLeftTime++
                if (mCurLeftTime == DataApi.mIntoBannerTimeArray[DataApi.mIntoBannerTimeIndex].toLong() && mHadChooseAdapter.data.size == 0) {
                    /*过了N秒后，而且购物车是空的，进入待机*/
                    EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_STATUS_YES_AWAIT, 1))
                }
                if (mCurLeftTime >= DataApi.mIntoBannerTimeArray[DataApi.mIntoBannerTimeIndex].toLong() && mHadChooseAdapter.data.size == 0) {
                    /*按了购物车是空的，过了N秒进入待机*/
                    mCurLeftTime = 0
                }
                //CommUtils.println("pollingLeftTime2Await::", "mCurLeftTime:$mCurLeftTime")
            } catch (exc: Exception) {
            }
            e.onComplete()
        })
            .repeatWhen { return@repeatWhen it.flatMap { return@flatMap Observable.timer(1, TimeUnit.SECONDS) } }
            .compose(RxUtils.nThread())
            .subscribe(object : Observer<String> {
                override fun onComplete() {}
                override fun onSubscribe(d: Disposable) {
                    mDisposable = d
                }

                override fun onNext(t: String) {}
                override fun onError(e: Throwable) {}
            })
    }


    /*初始化待机的 显示的二维码*/
    private fun initAwaitQrIv() {
        if (DataApi.mViceAwaitOnlineUrlQr.isNullOrBlank()) {
            mAwaitOnlineQrIv?.setImageResource(R.drawable.empty_su_yuan_qr)
        } else {
            mAwaitOnlineQrIv?.setImageBitmap(
                ZXingUtils.createQRCodeBitmap(
                    DataApi.mViceAwaitOnlineUrlQr, 500,
                    "UTF-8",
                    "H",
                    "2",
                    Color.BLACK,
                    Color.WHITE,
                    null, null, 0.2f
                )
            )
        }
        mAwaitAboutMeQrIv?.setImageBitmap(
            ZXingUtils.createQRCodeBitmap(
                DataApi.mViceAwaitOfficialUrlQr, 500,
                "UTF-8",
                "H",
                "2",
                Color.BLACK,
                Color.WHITE,
                null, mAppLogoBitmap, 0.2f
            )
        )
        mAwaitOnlineTipsTv?.text = DataApi.mViceAwaitOnlineTips
        mAwaitLeftBottomTipsAtv?.text = DataApi.mViceAwaitOfficialTips
    }

    @SuppressLint("SetTextI18n")
    private fun initShopInfo() {
        // 一般获取到新数据再刷新。
        mLogoIv?.let {
            if (DataApi.mShopLogoUrl.isNullOrBlank()) {
                it.setImageResource(R.drawable.shop_head_pic_default)
            } else {
                ImageManger.setCircleImg(mContext, DataApi.mShopLogoUrl, it)
            }
        }
        mAwaitLogoIv?.let {
            if (DataApi.mShopLogoUrl.isNullOrBlank()) {
                it.setImageResource(R.drawable.shop_head_pic_default)
            } else {
                ImageManger.setCircleImg(mContext, DataApi.mShopLogoUrl, it)
            }
        }

        mContactNameAtv?.text = DataApi.mShopUserName
        mAwaitContactNameAtv?.text = DataApi.mShopUserName
        mStallNameAtv?.text = DataApi.mShopStallName
        mAwaitStallNameAtv?.text = DataApi.mShopStallName
        mMyRB?.setStar(DataApi.mShopStart)
        mAwaitMyRB?.setStar(DataApi.mShopStart)
    }

    private fun initRightBottomBanner() {
        mRightBottomBanner
            ?.setBannerStyle(BannerConfig.NOT_INDICATOR)
            ?.setImageLoader(object : ImageLoader() {
                override fun displayImage(context: Context?, path: Any?, imageView: ImageView) {
                    imageView.scaleType = ImageView.ScaleType.FIT_CENTER
                    //TODO:这里需要获取图片的宽高来识别，从而是用FitCenter还是CenterCrop
                    d("initRightBottomBanner:path:$path")
                    imageView.post { ImageManger.setCenterCropImg(mContext, path as String, imageView, 300) }
                }
            })
    }

    /*右边底部文字滚动*/
    private fun initBottomBanner(tipsList: MutableList<String>?) {
        if (tipsList == null || tipsList.isEmpty()) {
            mRightBottomTipsBanner?.visibility = View.GONE
        } else {
            mRightBottomTipsBanner?.visibility = View.VISIBLE
            mBottomBannerAdapter = BottomBannerAdapter(tipsList)
            mRightBottomTipsBanner
                ?.setAdapter(mBottomBannerAdapter)
                ?.setOrientation(MyBanner.VERTICAL)
                ?.setPageTransformer(ZoomOutPageTransformer())
                ?.setLoopTime(DataApi.mViceWeightBottomTipsLoopTime * 1000L)
                ?.start()
        }
    }

    private fun initOrderRcy() {
        (mHadChooseRecyclerView?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mHadChooseRecyclerView?.addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL_LIST, 1, ContextCompat.getColor(App.context!!, R.color.c6)))
        mHadChooseAdapter = HadChooseAdapter()
        mHadChooseRecyclerView?.layoutManager = LinearLayoutManager(mContext)
        mHadChooseRecyclerView?.adapter = mHadChooseAdapter
        mHadChooseAdapter.bindToRecyclerView(mHadChooseRecyclerView)
        mHadChooseAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)
        //读取缓存
        //mHadChooseAdapter.setNewData(mutableListOf(OrderProductDB(), OrderProductDB(), OrderProductDB(), OrderProductDB(), OrderProductDB(), OrderProductDB()))
    }

    private fun initTv() {
        var tf = Typeface.createFromAsset(mContext.assets, "DS-DIGIT-4.ttf")
        mRightWeightTv?.typeface = tf
        mSubTotalTv?.typeface = tf
        mRightUnitPriceTv?.typeface = tf
    }

    private fun initListener() {
        mRightWeightTv?.addTextChangedListener(object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                var weight = mRightWeightTv?.text?.toString()?.toDouble() ?: 0.0
                var unitPrice = mRightUnitPriceTv?.text?.toString()?.toDouble() ?: 0.0
                mSubTotalTv?.text = String.format(
                    "%.2f",
                    try {
                        BigDecimal(weight).multiply(BigDecimal(unitPrice)).toDouble()
                    } catch (e: Exception) {
                        0.0
                    }
                )
            }
        })
    }

    inner class HadChooseAdapter : BaseQuickAdapter<OrderProductDB, BaseViewHolder>(R.layout.item_vice_screen_order, null) {
        @SuppressLint("CheckResult")
        override fun convert(helper: BaseViewHolder, item: OrderProductDB) {
            var discount = if (item.discountPercent == 100) "" else " (折后${String.format("%.2f", item.discountPercent / 100.0 * (item.realPrice?.toDouble() ?: 0.0))})"
            helper
                .setText(R.id.item_tv1, String.format("%02d", helper.bindingAdapterPosition + 1))
                .setText(R.id.item_atv1, item.productName)
                .setText(R.id.item_atv2, item.weight)
                .setText(R.id.item_atv3, String.format("%.2f", item.realPrice?.toDouble() ?: 0.0).plus(discount))
                .setText(R.id.item_atv4, item.subTotalPrice)
        }
    }


    /**  EventBus注册   */
    override fun show() {
        super.show()
        EventBusUtil.register(this)
        mRightBottomTipsBanner?.start()
        mRightBottomBanner?.startAutoPlay()
        mBanner?.startAutoPlay()
        if (!DataApi.mIsShowViceBanner) {
            mNoAwaitRootLayout?.visibility = View.VISIBLE
            mAwaitRootLayout?.visibility = View.GONE
        } else {
            pollingLeftTime2Await()
            pollingMediaRequest()
        }
    }

    /**  EventBus解注册   */
    override fun dismiss() {
        try {
            Jzvd.releaseAllVideos()
        } catch (e: Exception) {
        }
        EventBusUtil.unregister(this)
        mRightBottomTipsBanner?.stop()
        mRightBottomBanner?.stopAutoPlay()
        mBanner?.stopAutoPlay()
        mDisposable?.dispose()
        super.dismiss()
    }

    /*循环切换媒体播放、图片播放*/
    @SuppressLint("CheckResult")
    private fun pollingMediaRequest() {
        mMediaDisposable?.dispose()
        Observable.create(ObservableOnSubscribe<String> { e ->
            EventBusUtil.sendEvent(Event(EventCode.UPDATE_MEDIAL_UI))
            mMediaCount++
            e.onComplete()
        })
            .repeatWhen { return@repeatWhen it.flatMap { return@flatMap Observable.timer(1, TimeUnit.SECONDS) } }
            .subscribe(object : Observer<String> {
                override fun onComplete() {}
                override fun onSubscribe(d: Disposable) {
                    mMediaDisposable = d
                }

                override fun onNext(t: String) {}
                override fun onError(e: Throwable) {}
            })
    }

    private fun updateMediaUi() {
        //0图片和视频循环轮播", 1仅播放图片", 2仅播放视频
        when (DataApi.mBannerPlayTypeIndex) {
            //仅图片形式
            1 -> {
                mBanner?.visibility = View.VISIBLE
                mEmptyFoodLayout?.visibility = View.GONE
                mJzVideo?.visibility = View.GONE
                if (DataApi.mViceAwaitBannerListData.isEmpty()) {
                    mEmptyFoodLayout?.visibility = View.VISIBLE
                    mBanner?.visibility = View.GONE
                }
            }
            //仅食品模式
            2 -> {
                mBanner?.visibility = View.GONE
                mEmptyFoodLayout?.visibility = View.GONE
                mJzVideo?.visibility = View.VISIBLE
                if (DataApi.mVideoBean == null) {
                    mEmptyFoodLayout?.visibility = View.VISIBLE
                    mJzVideo?.visibility = View.GONE
                }
            }
            else -> {
                //图片和视频轮播
                when (mCurPlayType) {
                    PLAY_TYPE_VIDEO -> {
                        mBanner?.visibility = View.GONE
                        mEmptyFoodLayout?.visibility = View.GONE
                        mJzVideo?.visibility = View.VISIBLE
                        //mJzVideo?.startVideoAfterPreloading()
                        if (mMediaCount % DataApi.mPlayTimeVideo == 0) {
                            if (DataApi.mViceAwaitBannerListData.isNotEmpty()) {
                                mMediaCount = 1
                                mCurPlayType = PLAY_TYPE_BANNER
                            }
                        }
                    }
                    PLAY_TYPE_BANNER -> {
                        mBanner?.visibility = View.VISIBLE
                        mEmptyFoodLayout?.visibility = View.GONE
                        mJzVideo?.visibility = View.GONE
                        //mJzVideo?.startVideoAfterPreloading()
                        if (mMediaCount % DataApi.mPlayTimeBanner == 0) {
                            if (DataApi.mVideoBean != null) {
                                mMediaCount = 1
                                mCurPlayType = PLAY_TYPE_VIDEO
                            }
                        }
                    }
                    else -> {
                        //TODO：先看看有木有数据
                        when {
                            DataApi.mVideoBean != null -> mCurPlayType = PLAY_TYPE_VIDEO
                            DataApi.mViceAwaitBannerListData.isNotEmpty() -> mCurPlayType = PLAY_TYPE_BANNER
                            else -> showEmpty()
                        }
                    }
                }
            }
        }
    }

    /*显示空白数据*/
    private fun showEmpty() {
        mJzVideo?.visibility = View.GONE
        mBanner?.visibility = View.GONE
        mEmptyFoodLayout?.visibility = View.VISIBLE
    }

    /*显示广告图*/
    private fun setBannerData() {
        mBanner?.stopAutoPlay()
        if (DataApi.mViceAwaitBannerListData.isNotEmpty()) {
            mBanner?.setImages(DataApi.mViceAwaitBannerListData)
                ?.setBannerAnimation(CommUtils.getBannerAnimation(DataApi.mViceAwaitBannerAnimationType))
                ?.setDelayTime(DataApi.mPerBannerImgStayTimeArray[DataApi.mPerBannerImgStayTimeIndex].toInt() * 1000)
                ?.start()
        }
    }

    /*显示视频*/
    private fun setVideoData() {
        //边播放边缓存
        var url = App.getProxy(mContext)?.getProxyUrl(DataApi.mVideoBean?.videoUrl);
        val jzDataSource = JZDataSource(url, DataApi.mVideoBean?.title ?: "")

        jzDataSource.looping = true
        mJzVideo?.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL)
        mJzVideo?.fullscreenButton?.apply {
            visibility = View.INVISIBLE
            this.isClickable = false
        }
        mJzVideo?.topContainer?.visibility = View.GONE
        mJzVideo?.loadingProgressBar?.visibility = View.GONE
        /*预览图*/
        mJzVideo?.posterImageView?.let { ImageManger.setCenterCropImg(mContext, DataApi.mVideoBean?.imageUrl, it) }

        try {
            mJzVideo?.startVideoAfterPreloading();
            //mJzVideo?.startPreloading()
        } catch (e: Exception) {
            CommUtils.println("视频播放对象->", "Exception:$e")
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN) fun onEventBusCome(event: Event<Any>?) {
        if (event == null) return
        try {
            when (event.code) {
                EventCode.VICE_SCREEN_WEIGHT_NUMBER -> mRightWeightTv?.text = event.data as String
                EventCode.VICE_SCREEN_UPDATE_DATA -> updateProductData(event.data as ViceBean)
                EventCode.UPDATE_MEDIAL_UI -> updateMediaUi()
                EventCode.VICE_SCREEN_STATUS_YES_AWAIT -> go2YesAwait()
                EventCode.VICE_SCREEN_STATUS_NO_AWAIT -> go2NoAwait()
                EventCode.ORDER_UPDATE_TRACE_URL -> updateTraceQrUrl(event.data as ResponsePay)
                EventCode.ORDER_ON_PAY_VIP -> updatePayIv(mVipPayLayout, event.data as ServerOrderResult)
                EventCode.ORDER_ON_PAY_JUHE -> updatePayIv(mJuHeDynamicPayLayout, event.data as ServerOrderResult)
                EventCode.VICE_SCREEN_SHOW_STATICE_PAY -> showStaticPayIv()
                EventCode.ORDER_CANCEL -> cancelOrder()
                EventCode.SYNC_NEW_DATA -> updateAllData(false)
                else -> {}
            }
        } catch (e: Exception) {
            ToastUtil.showToast("副屏报错：$e")
        }
    }

    private fun updateProductData(viceBean: ViceBean) {
        mChooseFoodAtv?.text = viceBean.curName
        mRightUnitPriceTv?.text = viceBean.unitPrice
        mTotalPriceTv?.text = viceBean.totalPrice
        mHadChooseAdapter.setNewData(viceBean.list)
    }

    /*刷新 溯源订单二维码地址*/
    @SuppressLint("SetTextI18n")
    private fun updateTraceQrUrl(resp: ResponsePay) {
//        if (resp.gain_integral == null) {
//            mIntegralAndTraceTv?.text = "积分与溯源"
//            mIntegralAndTraceTv?.setTextColor(CommUtils.getColor(R.color.G567485))
//        } else {
//            mIntegralAndTraceTv?.text = "扫码获取 ${resp.gain_integral} 积分"
//            mIntegralAndTraceTv?.setTextColor(CommUtils.getColor(R.color.red_FF0000))
//        }

        /*设置积分溯源码*/
        var qrUrl = resp.qr_trace_url ?: DataApi.mShopWetchQrUrl
        if (qrUrl.isNullOrBlank()) {
            mIntegralAndTraceTv?.text = "一户一码"
            mIntegralAndTraceIv?.setImageResource(R.drawable.empty_su_yuan_qr)
        } else {
            mIntegralAndTraceTv?.text = "扫码积分/溯源"
            setImageViewQR(mIntegralAndTraceIv, qrUrl, mAppLogoBitmap)
        }


//        //支付码
//        when (PayUtils.mCurPayType) {
//            PayUtils.PAY_TYPE_CASH -> {
//                //显示默认静态码
//                showStaticPayIv()
//            }
//            PayUtils.PAY_TYPE_VIP_QR -> {
//                updatePayIv(mVipPayLayout)
//                mVipPayTv?.text = "请付款 ${resp.use_price} 元"
//                setImageViewQR(mVipPayIv, resp.qr_pay_url)
//            }
//            PayUtils.PAY_TYPE_JUHE_QR -> {
//                updatePayIv(mJuHeDynamicPayLayout)
//                when (resp.pay_result) {
//                    /*未支付*/
//                    ResponsePay.PAY_RESULT_NOT_PAY -> {
//                        mJuHeDynamicPayTv?.text = "请付款 ${resp.use_price} 元"
//                        setImageViewQR(mJuHeDynamicPayIv, resp.qr_pay_url)
//                    }
//                    /*支付成功，扫码获取积分*/
//                    ResponsePay.PAY_RESULT_SUCCESS -> {
//                        mJuHeDynamicPayTv?.text = "扫码获得 ${resp.gain_integral} 积分"
//                        setImageViewQR(mJuHeDynamicPayIv, resp.qr_trace_url)
//                    }
//                }
//            }
//        }
    }


    /*显示默认静态码*/
    private fun showStaticPayIv() {
        //根据数据，是否存在静态、动态二维码，才显示相应的二维码
        if (DataApi.mStaticPayJuHeUrl == null || DataApi.mStaticPayJuHeUrl!!.isEmpty()) {
            updatePayIv(mWetchAliPayLayout)

        } else {
            updatePayIv(mJuHeStaticPayLayout)
        }
    }

    /*根据数据刷新动态码*/
    @SuppressLint("SetTextI18n")
    private fun updatePayIv(view: View?, serverOrderResult: ServerOrderResult? = null) {
        //到时接入数据时候，统一在此处理
        mWetchAliPayLayout?.visibility = View.GONE
        mJuHeStaticPayLayout?.visibility = View.GONE
        mJuHeDynamicPayLayout?.visibility = View.GONE
        mVipPayLayout?.visibility = View.GONE
        view?.visibility = View.VISIBLE
        mBottomTipsTv?.text = DataApi.mCompanyTips
        when (view) {
            mWetchAliPayLayout -> {
                /*静态 微信码*/
                setImageViewQR(mWetchPayIv, DataApi.mStaticPayWetchUrl)
                /*静态 支付宝码*/
                setImageViewQR(mAliPayIv, DataApi.mStaticPayAliUrl)
                //背景图
                mWetchPayBgIv?.let { if (DataApi.mStaticPayWetchBgUrl.isNullOrBlank()) it.setImageResource(R.drawable.static_wetch_pay_bg) else ImageManger.setFitCenterImg(mContext, DataApi.mStaticPayWetchBgUrl, it) }
                mAliPayBgIv?.let { if (DataApi.mStaticPayAliBgUrl.isNullOrBlank()) it.setImageResource(R.drawable.static_ali_pay_bg) else ImageManger.setFitCenterImg(mContext, DataApi.mStaticPayAliBgUrl, it) }

                if (serverOrderResult?.integral_url != null && serverOrderResult.integral_url!!.isNotBlank()) {
                    /*显示积分二维码*/
                    //mIntegralAndTraceTv?.text = "积分与溯源"
                    mIntegralAndTraceTv?.text = "扫码积分/溯源"
                    setImageViewQR(mIntegralAndTraceIv, serverOrderResult.integral_url, mAppLogoBitmap)
                } else {
                    //mIntegralAndTraceTv?.text = "关注公众号"
                    mIntegralAndTraceTv?.text = "一户一码"
                    if (DataApi.mShopWetchQrUrl.isNullOrBlank()) {
                        mIntegralAndTraceIv?.setImageResource(R.drawable.empty_su_yuan_qr)
                    } else {
                        setImageViewQR(mIntegralAndTraceIv, DataApi.mShopWetchQrUrl, mAppLogoBitmap)
                    }
                }
            }
            mJuHeStaticPayLayout -> {
                /*静态 聚合码*/
                //mIntegralAndTraceTv?.text = "关注公众号"
                mJuHeStaticPayBgIv?.let { ImageManger.setFitCenterImg(mContext, DataApi.mStaticPayJuHeBgUrl, it) }
                setImageViewQR(mJuHeStaticPayIv, DataApi.mStaticPayJuHeUrl)
            }
            mVipPayLayout -> {
                //开启轮询 先放第一位，因为下面会刷新微会员二维码
                //EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_POLLING_REQUEST_PAY_RESULT_START,serverOrderResult))//这里已经放在CollectMoneyActivity那里调用
                /*测试 动态 微会员*/
                mVipPayBgIv?.let { ImageManger.setFitCenterImg(mContext, DataApi.mDynamicPayVipBgUrl, it) }
                //这里设置显示动态为微会员二维码
                setImageViewQR(mVipPayIv, serverOrderResult?.qr_url, mAppLogoBitmap)

                mVipPayTv?.text = "请付款 ${serverOrderResult?.orderDB?.realPrice} 元"
                /*显示积分二维码*/
                //mIntegralAndTraceTv?.text = "积分与溯源"
                if (serverOrderResult?.integral_url != null && serverOrderResult.integral_url!!.isNotBlank()) {
                    mIntegralAndTraceTv?.text = "扫码积分/溯源"
                    setImageViewQR(mIntegralAndTraceIv, serverOrderResult.integral_url, mAppLogoBitmap)
                } else {
                    mIntegralAndTraceTv?.text = "一户一码"
                    if (DataApi.mShopWetchQrUrl.isNullOrBlank()) {
                        mIntegralAndTraceIv?.setImageResource(R.drawable.empty_su_yuan_qr)
                    } else {
                        setImageViewQR(mIntegralAndTraceIv, DataApi.mShopWetchQrUrl, mAppLogoBitmap)
                    }
                }
            }
            mJuHeDynamicPayLayout -> {
                //开启轮询 先放第一位，因为下面会刷新微会员二维码
                //EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_POLLING_REQUEST_PAY_RESULT_START,serverOrderResult)) //这里已经放在CollectMoneyActivity那里调用
                /*测试 动态 聚合码*/
                mJuHeDynamicPayBgIv?.let { ImageManger.setFitCenterImg(mContext, DataApi.mDynamicPayJuHeBgUrl, it) }
                //这里设置显示聚合二维码
                setImageViewQR(mJuHeDynamicPayIv, serverOrderResult?.qr_url, mAppLogoBitmap)
                mJuHeDynamicPayTv?.text = "请付款 ${serverOrderResult?.orderDB?.realPrice} 元"

                /*显示积分二维码*/

                if (serverOrderResult?.integral_url != null && serverOrderResult.integral_url!!.isNotBlank()) {
                    mIntegralAndTraceTv?.text = "扫码积分/溯源"
                    setImageViewQR(mIntegralAndTraceIv, serverOrderResult.integral_url, mAppLogoBitmap)
                } else {
                    mIntegralAndTraceTv?.text = "一户一码"
                    if (DataApi.mShopWetchQrUrl.isNullOrBlank()) {
                        mIntegralAndTraceIv?.setImageResource(R.drawable.empty_su_yuan_qr)
                    } else {
                        setImageViewQR(mIntegralAndTraceIv, DataApi.mShopWetchQrUrl, mAppLogoBitmap)
                    }
                }
            }
        }
    }


    private fun cancelOrder() {
        EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_POLLING_REQUEST_PAY_RESULT_CANCEL))
        showStaticPayIv()
    }

    fun d(msg: String) {
        CommUtils.println("${ViceScreenDisplay}->", msg)
    }

    /*设置ImageView加载显示二维码*/
    private fun setImageViewQR(imageView: ImageView?, qrUrl: String?, bm: Bitmap? = null) {
        imageView?.let {
            if (qrUrl.isNullOrBlank()) {
                imageView.setImageResource(R.drawable.empty_su_yuan_qr)
            } else {
                val createQRCodeBitmap = ZXingUtils.createQRCodeBitmap(
                    qrUrl, 500, "UTF-8", "H", "2", Color.BLACK, Color.WHITE, null, bm, 0.2f
                )
                it.setImageBitmap(createQRCodeBitmap)
            }
        }
    }

    /*退出待机待机*/
    private fun go2NoAwait() {
        mCurLeftTime = 0
        mAwaitRootLayout?.visibility = View.GONE
        mNoAwaitRootLayout?.visibility = View.VISIBLE
    }

    /*进入待机*/
    private fun go2YesAwait() {
        if (DataApi.mIsShowViceBanner) {
            mNoAwaitRootLayout?.visibility = View.GONE
            mAwaitRootLayout?.visibility = View.VISIBLE
        } else {
            mCurLeftTime = 0
            mAwaitRootLayout?.visibility = View.GONE
            mNoAwaitRootLayout?.visibility = View.VISIBLE
        }
    }
}